package com.xjscrm.console.chat.queue;

import com.xjscrm.console.biz.SysTenantService;
import com.xjscrm.console.config.datasource.DynamicDataSourceContextHolder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.concurrent.Executor;

/**
 * @author mingyang.chen create in 2024/3/25 19:14
 */
@Component
@Slf4j
public class ChatRecvDelayConsumer implements Runnable {

    @Autowired
    private Executor chatExecutor;

    @Autowired
    private SysTenantService sysTenantService;

    @PostConstruct
    public void start() {
        chatExecutor.execute(this);
    }

    @Override
    public void run() {
        log.info("启动客户回复超时消息延时队列消费器.....");
        for (; ; ) {
            try {
                ChatDelayTask take;
                try {
                    take = ChatDelayProducer.getRecvDelayQueue().take();
                } catch (InterruptedException e) {
                    log.error("从客户回复超时延时队列中获取任务失败");
                    continue;
                }
                log.info("获取客户回复超时延迟任务: {}", take);
                chatExecutor.execute(() -> {
                    String tenantCodeByMerId = sysTenantService.getTenantCodeByMerId(take.getMerId());
                    try {
                        DynamicDataSourceContextHolder.setDataSourceKey(tenantCodeByMerId);
                        take.getRunnable().run();
                    } finally {
                        DynamicDataSourceContextHolder.clearDataSourceKey();
                    }
                });
            } catch (Exception e) {
                log.error("客户回复超时延时队列消费出现异常", e);
            }
        }
    }
}
